package com.kedacom.freedomLabel.view.activity.report;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.arch.lifecycle.ViewModelProviders;
import android.databinding.ViewDataBinding;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.kedacom.freedomLabel.AppExecutors;
import com.kedacom.freedomLabel.BR;
import com.kedacom.freedomLabel.Options;
import com.kedacom.freedomLabel.R;
import com.kedacom.freedomLabel.base.BaseFragment;
import com.kedacom.freedomLabel.databinding.FragmentReportDetailBinding;
import com.kedacom.freedomLabel.databinding.ItemReportDetailBinding;
import com.kedacom.freedomLabel.excel.ISheetRecord;
import com.kedacom.freedomLabel.model.bean.Business;
import com.kedacom.freedomLabel.model.bean.SharedFile;
import com.kedacom.freedomLabel.model.excel.BaseDataTable;
import com.kedacom.freedomLabel.model.excel.BusinessSheet;
import com.kedacom.freedomLabel.utils.ExcelUtils;
import com.kedacom.freedomLabel.utils.FileHelp;
import com.kedacom.freedomLabel.utils.log.LLog;
import com.kedacom.freedomLabel.view.activity.ExportDataActivity;
import com.kedacom.freedomLabel.viewmodel.report.ReportDetailViewModel;
import com.kedacom.freedomLabel.viewmodel.report.ReportSummaryViewModel;
import com.kedacom.lego.adapter.recyclerview.LegoBaseRecyclerViewAdapter;
import com.kedacom.lego.annotation.ContentView;
import com.kedacom.lego.annotation.ViewModel;
import com.kedacom.lego.message.LegoMessageManager;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

@ContentView(R.layout.fragment_report_detail)
@ViewModel(ReportSummaryViewModel.class)
public class ReportDetailFragment extends BaseFragment<FragmentReportDetailBinding, ReportDetailViewModel> {
    private LegoBaseRecyclerViewAdapter<Business> adapter;
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss", Locale.getDefault());

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View root = super.onCreateView(inflater, container, savedInstanceState);

        adapter = new LegoBaseRecyclerViewAdapter<Business>(R.layout.item_report_detail, new ArrayList<>(), BR.business) {
            @Override
            protected void onCustomBindItem(ViewDataBinding binding, int position) {
                super.onCustomBindItem(binding, position);
                ((ItemReportDetailBinding) binding).index.setText(String.valueOf(position + 1));
                ((ItemReportDetailBinding) binding).createTime.setText(sdf.format(new Date(adapter.getData().get(position).createTime)));

                if (adapter.getData().get(position).selected) {
                    ((ItemReportDetailBinding) binding).layout.setBackgroundColor(ContextCompat.getColor(getContext(),
                            R.color.item_selected_bg));
                } else {
                    ((ItemReportDetailBinding) binding).layout.setBackgroundColor(ContextCompat.getColor(getContext(),
                            position % 2 == 0 ? R.color.white_back : android.R.color.transparent));
                }
            }
        };
        adapter.setOnItemClickListener((view, o, i) -> {
            beep();

            Business business = (Business) o;
            if (((Business) o).selected) {
                mViewModel.selectNum.set(mViewModel.selectNum.getValue() - 1);
            } else {
                mViewModel.selectNum.set(mViewModel.selectNum.getValue() + 1);
            }
            business.selected = !business.selected;

            adapter.notifyItemChanged(i);
        });
        mBinding.recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mBinding.recyclerView.setAdapter(adapter);
        mBinding.back.setOnClickListener(v -> {
            beep();
            getActivity().getSupportFragmentManager().popBackStack();
        });

        mBinding.export.setOnClickListener(v -> {
            beep();
            exportData();
        });

        mBinding.removeAll.setOnClickListener(v -> {
            beep();
            removeAll();
        });

        mBinding.removeSelected.setOnClickListener(v -> {
            beep();
            removeSelected();
        });

        mViewModel.businessList.observe(this, businesses -> {
            adapter.setData(businesses);
        });

        if (getArguments() != null) {
            mViewModel.getSummaryDetail(getArguments().getLong("startTime"),
                    getArguments().getLong("endTime"),
                    getArguments().getString("productId"),
                    getArguments().getString("cardNumber"));
        }
        return root;
    }


    private void removeSelected() {
        new AlertDialog.Builder(getActivity())
                .setTitle("提示")
                .setMessage(String.format("是否刪除选中的这%s条数据？", mViewModel.selectNum.getValue()))
                .setNegativeButton("取消", (dialog, which) -> {
                    dialog.dismiss();
                })
                .setPositiveButton("删除", (dialog, which) -> {
                    beep();
                    List<Integer> ids = new ArrayList<>();

                    for (Business business : adapter.getData()) {
                        if (business.selected) {
                            ids.add(business.index);
                        }
                    }

                    mViewModel.delete(ids);
                })
                .show();
    }

    private void removeAll() {
        new AlertDialog.Builder(getActivity())
                .setTitle("警告")
                .setMessage(String.format("是否要清空这些数据？", mViewModel.selectNum.getValue()))
                .setNegativeButton("取消", (dialog, which) -> {
                    dialog.dismiss();
                })
                .setPositiveButton("删除", (dialog, which) -> {
                    beep();

                    if (getArguments() != null)
                        mViewModel.deleteAll(getArguments().getLong("startTime"),
                                getArguments().getLong("endTime"),
                                getArguments().getString("productId"),
                                getArguments().getString("cardNumber"));
                })
                .show();
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mViewModel.selectNum.observe(this, integer -> {
            mBinding.selectedNum.setText(String.format(Locale.getDefault(), "选中 %s 项", integer));
            mBinding.selectedNum.setVisibility((integer != null && integer > 0) ? View.VISIBLE : View.INVISIBLE);
            mBinding.removeSelected.setVisibility((integer != null && integer > 0) ? View.VISIBLE : View.INVISIBLE);
        });

        mViewModel.deleteResult.observe(this, deleteRes -> {
            if (deleteRes == null) {
                if (getArguments() != null)
                    mViewModel.getSummaryDetail(getArguments().getLong("startTime"),
                            getArguments().getLong("endTime"),
                            getArguments().getString("productId"),
                            getArguments().getString("cardNumber"));
                LegoMessageManager.getInstance().sendEmptyMessage(Options.MSG_REFRESH_REPORT);
            } else {
                showToast(deleteRes, TOAST_ERROR);
            }
        });
    }

    @Override
    public ReportDetailViewModel getViewModel() {
        return ViewModelProviders.of(this).get(ReportDetailViewModel.class);
    }

    /**
     * 数据导出
     */
    private void exportData() {

        if(getArguments()==null){
            showToast("argument为null",TOAST_ERROR);
            return;
        }
        String fileDir = getArguments().getString("fileDir");
        String fileName = getArguments().getString("fileName");

        if(TextUtils.isEmpty(fileDir) || TextUtils.isEmpty(fileName)){
            showToast("文件名或路径为null",TOAST_ERROR);
            return;
        }

        excelPd = new ProgressDialog(requireContext());
        excelPd.setTitle("数据生成中，请稍后...");
        excelPd.setCancelable(false);
        excelPd.setCanceledOnTouchOutside(false);
        excelPd.show();

        AppExecutors.getInstance().insertIO()
                .submit(() -> {
                    try {

                        File tempDir = new File(FileHelp.TEMP_EXCEL_DIR,fileDir);
                        if(!tempDir.exists())
                            tempDir.mkdirs();

                        BaseDataTable table = new BaseDataTable(fileName,
                                new ISheetRecord[]{
                                        new BusinessSheet(adapter.getData())
                                });
                        File tempExcelFile = new File(tempDir, fileName);
                        if (tempExcelFile.exists())
                            tempExcelFile.delete();

                        ExcelUtils.toExcel(tempDir.getAbsolutePath(), table);

                        if (tempExcelFile.exists()) { //文件存在时
                            excelSuccess(String.format(Locale.getDefault(), "生成成功：%s", fileName));
                            ExportDataActivity.startActivity(getActivity(), "报表导出", new SharedFile(tempExcelFile.getAbsolutePath(), fileName));
                        } else {
                            excelFail("导出失败，请重试。");
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        LLog.error(e.getMessage());
                        excelFail("导出失败，请重新拔插usb设备。");
                    }

                });
    }

    private void excelFail(String msg) {
        getActivity().runOnUiThread(() -> {
            if (excelPd != null && excelPd.isShowing())
                excelPd.dismiss();
        });
        showToast(msg, TOAST_ERROR);
    }

    private void excelSuccess(String msg) {
        getActivity().runOnUiThread(() -> {
            if (excelPd != null && excelPd.isShowing())
                excelPd.dismiss();
        });
//        showToast(msg, TOAST_SUCCESS);
    }

    private ProgressDialog excelPd;
}
